package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService{

    @Autowired
    private StrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment comment) {
        comment.setCreateTime(new Date());
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //1.创建查询对象
        Query query = new Query();
        //2.封装条件查询对象
        Criteria criteria = Criteria.where("detailId").is(qo.getDetailId());
        query.addCriteria(criteria);
        //3.查询总条数
        long count = template.count(query, StrategyComment.class);
        //long count = repository.count(query, StrategyComment.class);------>这个方法不行
        //4.封装分页查询对象
        //Pageable--->拿它的实现类
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1,
                qo.getPageSize(),
                Sort.Direction.DESC,
                "desc");
        query.with(pageRequest);
        //5.查询list
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        //返回Page实现类
        //PageImpl(List<T> content, Pageable pageable, long total)
        return new PageImpl(list,pageRequest,count);
    }

    @Override
    public void addThumbUp(String toid, Long fromid) {
        //1.通过id去查点赞列表
        StrategyComment strategyComment = repository.findById(toid).get();
        List<Long> thumbuplist = strategyComment.getThumbuplist();
        //2.如果列表中已存在用户id,则执行取消点赞操作,点赞数-1
        if(thumbuplist.contains(fromid)){
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()-1);
            thumbuplist.remove(fromid);
        }else {
            //3.如果不存在,则执行点赞操作,点赞数+1
            strategyComment.setThumbupnum(strategyComment.getThumbupnum()+1);
            thumbuplist.add(fromid);
        }
        //重新保存到数据库中
        repository.save(strategyComment);
    }



}
